import { loginApi, getMenuInfoList } from '@/api/user/login';
import { defineStore } from 'pinia';
import { UserState, getAuthInfo } from './typing';
import type { MenuInfo } from './typing';
import { LoginParams } from '@/api/user/login';
import { piniaPersistConfig } from '@/config/piniaPersist';
import { message } from 'ant-design-vue';
import { refreshRouter } from '@/router';
import { addRouterDynamicRouter } from '@/router/index';

// useStore could be anything like useUser, useCart
// the first argument is a unique id of the store across your application
export const useUserStore = defineStore('app-user', {
	state: (): UserState => ({
		userInfo: null,
		token: undefined,
		roleList: [],
		sessionTimeout: false,
		lastUpdateTime: 0,
		menuInfo: null,
		hasMenu: false,
		orgInfo: null,
		roleInfo: null,
	}),

	getters: {
		getUserInfo(): any {
			return this.userInfo || getAuthInfo('userInfo');
		},
		getToken(): string {
			let localStorage = window.localStorage;
			return this.token || localStorage.getItem('token') || '';
		},
		getMenuInfo(): MenuInfo[] | null {
			return this.menuInfo;
		},
		getSessionTimeout(): boolean {
			return !!this.sessionTimeout;
		},
		getLastUpdateTime(): number {
			return this.lastUpdateTime;
		},
		getRouteStatus(): Boolean {
			return this.hasMenu || localStorage.getItem('hasRoute') === 'true';
		},
		getRoleInfo(): any {
			return this.roleInfo;
		},
		getOrgInfo(): any {
			return this.orgInfo;
		},
	},
	actions: {
		setToken(info: string | undefined) {
			this.token = info ? info : '';
			localStorage.setItem('token', this.token);
		},
		setMenuInfo(info: MenuInfo[]) {
			this.menuInfo = info ? info : null;
		},
		changeRouteStatus(state: any) {
			this.hasMenu = state;
			localStorage.setItem('hasRoute', state);
		},
		//设置用户信息
		setUserInfo(admin: any) {
			this.userInfo = admin;
		},
		setRoleInfo(roleInfo: any) {
			this.roleInfo = roleInfo;
		},
		setOrgInfo(orgInfo: any) {
			this.orgInfo = orgInfo;
		},
		async login(
			params: LoginParams & {
				goHome?: boolean;
			},
		) {
			//  ): Promise<GetUserInfoModel | null> {
			try {
				const { goHome = true, ...loginParams } = params;
				const data = await loginApi(loginParams);
				if (data.code == '200') {
					await refreshRouter();
					this.changeRouteStatus(false);
					const { token } = data.data;
					let admin = data.data;
					// save userInfo
					this.setUserInfo(admin);
					// save token
					this.setToken(token);
					const { code, data: menuData } = await getMenuInfoList({});
					if (code == '200') {
						this.setMenuInfo(menuData);
					}
					await addRouterDynamicRouter();
					this.setRoleInfo(admin?.roleInfoVo);
					this.setOrgInfo(admin?.orgInfoVo);
					return admin;
				} else {
					message.error((data && data.message) || '删除失败！', 3);
				}
			} catch (error: any) {
				message.error(error?.message || '登录失败，请联系管理员', 3);
				return Promise.reject(error);
			}
		},
	},
	persist: piniaPersistConfig('app-user'),
});
